package com.train.springboot.springboottrain.interceptor;

import com.train.springboot.springboottrain.config.SystemConfig;
import com.train.springboot.springboottrain.model.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器--------------------------------------");


        //拦截的规则
        //从session中获取用户的信息
        User user = (User) request.getSession().getAttribute("user");

        //判断用户是否为空
        if (null == user){
            //未登录
            response.sendRedirect(request.getContextPath() + "/user/page/login");
            return false;
        }
        return true;
    }
/*
    在 项 目 中 创 建 一 个 config 包，创建 一 个 配 置 类 SystemConfig， 并 实 现
    WebMvcConfigurer 接口， 覆盖接口中的 addInterceptors 方法，并为该配置类添加
    @Configuration
    注解，标注此类为一个配置类，让 Spring Boot 扫描到，这里的操作就相当
    于 SpringMVC 的注册拦截器 ，@Configuration 就相当于一个 applicationContext-mvc.xml*/





    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
